using System.Collections.Generic;
using UnityEngine;



public class RelicManager : MonoBehaviour {
    [Header("配置遗物引用")]
    public RelicConfig relicConfig;
    [Header("系统引用")]
    public PlayerData player;
    public EffectSystem effectSystem;
    public BattleManager battleManager;
    // 当前激活的遗物逻辑对象列表
    private List<Relic> activeRelics = new List<Relic>();
    private void Start()
    {
        // 确保引用存在
        if (player == null) player = FindObjectOfType<PlayerData>();
        if (effectSystem == null) effectSystem = FindObjectOfType<EffectSystem>();
        if (battleManager == null) battleManager = FindObjectOfType<BattleManager>();

        // 订阅系统事件 (Observer Pattern)
        SubscribeToEvents();
    }
    private void SubscribeToEvents()
    {
        // 1. 订阅 EffectSystem 事件
        if (effectSystem != null)
        {
            EffectSystem.OnBlockGained += HandleBlockGained;
        }
        
        // 原因：BattleManager 采用的是直接调用的方式，
        // 而不是广播事件的方式。因此这里不需要订阅，否则会报错。
    }
    private void OnDestroy()
    {
        // 取消订阅
        EffectSystem.OnBlockGained -= HandleBlockGained;
    }
    // === 遗物实例化与初始化 ===
    
    /// <summary>
    /// 根据 PlayerData 中的 ID 列表初始化遗物 ,在战斗场景加载时调用
    /// </summary>
    public void InitializeRelics()
    {
        activeRelics.Clear();
        foreach (string relicId in player.relics)
        {
            CreateAndAddRelic(relicId);
        }
        Debug.Log($"[RelicManager] 初始化完成，共加载 {activeRelics.Count} 个遗物。");
    }
    private void CreateAndAddRelic(string id)
    {
        RelicData data = relicConfig.GetRelicData(id);
        if (data == null) return;

        Relic relic = null;
        
        // 简单的工厂逻辑
        switch (id)
        {
            case "vajra": relic = new VajraRelic(data); break;
            case "anchor": relic = new AnchorRelic(data); break;
            // default: relic = new DefaultRelic(data); break; // 默认无效果遗物
        }

        if (relic != null)
        {
            relic.Initialize(player, effectSystem, battleManager);
            activeRelics.Add(relic);
        }
    }
    // === 事件分发处理 ===

    // 供外部(BattleManager)直接调用的手动钩子
    public void OnBattleStart()
    {
        foreach (var relic in activeRelics) relic.OnBattleStart();
    }

    public void OnTurnStart()
    {
        foreach (var relic in activeRelics) relic.OnTurnStart();
    }

    // 自动响应 EffectSystem 事件
    private void HandleBlockGained(ITarget target, int amount)
    {
        // 目前涉及只关心玩家获得的格挡 
        if (target == player)
        {
            foreach (var relic in activeRelics) relic.OnBlockGained(target, amount);
        }
    }
}